﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using 软件运行平台.ViewModel;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Net;
using ICSharpCode.SharpZipLib.Zip;
using MengXunAppTool.Helper;
using MengXunAppTool.DAL;
using MengXunAppTool.BLL;
using HandyControl.Tools.Extension;

namespace 软件运行平台.View
{
    /// <summary>
    /// UserControlCustomers.xaml 的交互逻辑
    /// </summary>
    public partial class AppsView : UserControl
    {

        private static class Status
        { 
            public static SolidColorBrush NotDownloaded = new SolidColorBrush(Color.FromRgb(182, 200, 214));
            public static SolidColorBrush NotUpgraded = new SolidColorBrush(Color.FromRgb(245, 159, 9));
            public static SolidColorBrush Operational = new SolidColorBrush(Color.FromRgb(89, 207, 105));
            public static SolidColorBrush Check = Brushes.Tomato;
        }

        private List<Sql3Helper.MX_AppVerRecord> _apps;
        private MainWindow _mainWindow;
        private ConfigHelper configHelper = new ConfigHelper();
        private VerDAL verDAL = new VerDAL();
        private RunDAL runDAL = new RunDAL();
        private FtpBLL ftp = new FtpBLL();
        private ShenPiDAL shenPiDAL = new ShenPiDAL();
        public AppsView(List<Sql3Helper.MX_AppVerRecord> apps,MainWindow mainWindow)
        {
            InitializeComponent();
            _apps = apps;
            _mainWindow = mainWindow;
            GridAddButton();
        }
        private void GridAddButton()
        {
            try
            {
                int row = 0;
                int column = 0;
                SoftGrid.RowDefinitions.Add(new RowDefinition());
                Dictionary<string, string> dic = configHelper.ReadAll();
                string localDir = dic["LocalDir"] + ":\\MX_APP";
                foreach (var item in _apps)
                {
                    TextBlock textBlock = new TextBlock()
                    {
                        Text = item.AppName + item.Version,
                        TextAlignment = TextAlignment.Center,
                        TextWrapping = TextWrapping.Wrap,
                        VerticalAlignment = VerticalAlignment.Center,
                        Foreground = new SolidColorBrush(Colors.Snow)
                    };
                    Button button1 = new Button()
                    {
                        Content = textBlock,
                        Margin = new Thickness(10, 10, 10, 10),
                        Height = 95,
                        FontSize = 20,
                        Focusable=false
                    };
                    button1.Name = "FTP" + item.id.ToString();
                    button1.Foreground = new SolidColorBrush(Colors.Snow);
                    button1.Background = Status.NotDownloaded;
                    if (string.IsNullOrEmpty(item.LocalPath) == false && Directory.Exists(item.LocalPath))
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(item.LocalPath);
                        if (directoryInfo.GetFiles().Length > 0)
                        {
                            button1.Background = Status.NotUpgraded;
                            if (directoryInfo.CreationTime > item.ReleaseTime)
                            {
                                button1.Background = Status.Operational;
                                button1.Name = "LOCAL" + item.id.ToString();
                            }
                        }
                    }
                    else if (Directory.Exists(localDir + "\\" + item.Customer + "\\" + item.Product + "\\" + item.AppName))
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(localDir + "\\" + item.Customer + "\\" + item.Product + "\\" + item.AppName);
                        if (directoryInfo.GetDirectories().Length > 0)
                        {
                            button1.Background = Status.NotUpgraded;
                            string localPath = localDir + "\\" + item.Customer + "\\" + item.Product + "\\" + item.AppName + "\\" + item.AppName + item.Version;
                            if (Directory.Exists(localPath))
                            {
                                DirectoryInfo locaDirec = new DirectoryInfo(localPath);
                                if (locaDirec.CreationTime > item.ReleaseTime)
                                {
                                    button1.Background = Status.Operational;
                                    button1.Name = "LOCAL" + item.id.ToString();
                                }
                            }
                        }
                    }
                    if (_mainWindow.IsQE)
                    {
                        button1.Background = Status.Check;
                    }
                    button1.Click += new System.Windows.RoutedEventHandler(this.ButtonClick);
                    button1.SetValue(Grid.RowProperty, row);
                    button1.SetValue(Grid.ColumnProperty, column);
                    SoftGrid.Children.Add(button1);
                    column++;
                    if (column == 4)
                    {
                        row++;
                        column = 0;
                        SoftGrid.RowDefinitions.Add(new RowDefinition());
                    }
                }
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString() );
            }

        }
        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                Button button = sender as Button;
                string id = button.Name.Replace("FTP", "");
                id = id.Replace("LOCAL", "");
                Sql3Helper.MX_AppVerRecord model = verDAL.GetApp(int.Parse(id));
                Dictionary<string, string> dic = configHelper.ReadAll();
                string localDir = dic["LocalDir"] + ":\\MX_APP" + model.FtpPath.Substring(0, model.FtpPath.LastIndexOf('\\')).Replace("发布软件", "");
                string exePath = localDir + "\\" + model.AppName + model.Version + model.ExePath;
                if (string.IsNullOrEmpty(model.LocalPath) == false)
                {
                    localDir = model.LocalPath;
                    exePath = localDir + model.ExePath;
                }
                if (button.Background == Status.Check)
                {
                    if (!Directory.Exists(localDir))
                    {
                        Directory.CreateDirectory(localDir);
                    }
                    string localPath = localDir + "\\" + model.AppName + "V0.0";
                    exePath = localDir + "\\" + model.AppName + "V0.0" + model.ExePath;
                    //if (string.IsNullOrEmpty(model.LocalPath) == false)
                    //{
                    //    localPath = model.LocalPath;
                    //    exePath = localDir + "\\" + model.ExePath;
                    //}
                    if (Directory.Exists(localPath))
                    {
                        DirectoryInfo oldDir = new DirectoryInfo(localPath);
                        if (oldDir.CreationTime > model.ReleaseTime)
                        {
                            Process process1 = new Process();
                            process1.StartInfo.WorkingDirectory = exePath.Substring(0, exePath.LastIndexOf('\\'));
                            process1.StartInfo.FileName = exePath.Substring(exePath.LastIndexOf('\\') + 1);
                            Sql3Helper.MX_AppRunRecord mX_Run = new Sql3Helper.MX_AppRunRecord()
                            {
                                Appid = model.id,
                                AppName = model.AppName,
                                Customer = model.Customer,
                                Product = model.Product,
                                Version = model.Version
                            };
                            if (string.IsNullOrEmpty(model.Login) == false)
                            {
                                var view = new View.LogInView(model.Login);
                                bool? isIn = view.ShowDialog();
                                this.Focus();
                                if (isIn == false)
                                {
                                    return;
                                }
                                mX_Run.User = MainWindow.userModel?.nickName;
                            }
                            runDAL.InsertMX_AppRunRecord(mX_Run);
                            process1.Start();
                            //todo 弹窗
                            //提示 是，否，取消
                            //MessageBoxResult result = HandyControl.Controls.MessageBox.Show(
                            // "测试完成，是否进行复测？\r\n是：复测；\r\n否：开始老化;\r\n取消：退出老化", "发现有产品测试未通过", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                            //取消
                            Task.Factory.StartNew(() =>
                            {
                                try
                                {
                                    MessageBoxResult result =
                                        HandyControl.Controls.MessageBox.Show($"{model.Customer}{model.Product}\r\n{model.AppName}{model.Version}\r\n是否审批通过，上线使用？",button:MessageBoxButton.YesNoCancel,icon:MessageBoxImage.Question);
                                    //todo 推送 数据库
                                    if (result == MessageBoxResult.Yes)
                                    {
                                        string msg = $"软件平台通知：\r\n\r\n{model.Customer}\r\n{model.Product}\r\n{model.AppName}{model.Version}\r\n\r\n{model.ReleaseLog}\r\n\r\n{model.CheckUser1}审批通过\r\n可下载使用";
                                        string err = "";
                                        List<string> ids = new List<string> { shenPiDAL.GetId(model.CheckUser1), shenPiDAL.GetId(model.CheckUser2), shenPiDAL.GetId(model.ReleaseUser) };            
                                        foreach (var item in model.PushUser.Split(new char[] { ','},StringSplitOptions.RemoveEmptyEntries))
                                        {
                                            ids.Add(shenPiDAL.GetId(item));
                                        }
                                        bool send = MesTool.UserBLL.SendMsg(msg, ref err, ids);
                                        if (send == false)
                                        {
                                            HandyControl.Controls.Growl.Error("推送失败：\r\n" + err);
                                            return;
                                        }
                                        shenPiDAL.SetCheck(model.id);
                                        SoftGrid.Dispatcher.Invoke(() =>
                                        {
                                            //推送OK
                                            button.Visibility = Visibility.Hidden;
                                        });
                                    }
                                    if (result == MessageBoxResult.No)
                                    {
                                        string msg = $"软件平台通知：\r\n\r\n{model.Customer}\r\n{model.Product}\r\n{model.AppName}{model.Version}\r\n\r\n{model.ReleaseLog}\r\n\r\n{model.CheckUser1}审批未通过\r\n请{model.ReleaseUser}确认";
                                        string err = "";
                                        List<string> ids = new List<string> { shenPiDAL.GetId(model.CheckUser1), shenPiDAL.GetId(model.CheckUser2), shenPiDAL.GetId(model.ReleaseUser) };
                                        bool send = MesTool.UserBLL.SendMsg(msg, ref err, ids);
                                        if (send == false)
                                        {
                                            HandyControl.Controls.Growl.Error("推送失败：\r\n" + err);
                                            return;
                                        }
                                    }
                                }
                                catch (Exception ee)
                                {
                                    SoftGrid.Dispatcher.Invoke((Action)delegate
                                    {
                                        HandyControl.Controls.Growl.Error(ee.Message.ToString());
                                        LogHelper.WriteLog(ee.ToString());
                                    });
                                }
                            });
                            return;
                        }
                        oldDir.Delete(true);
                    }
                    DirectoryInfo baseDir = new DirectoryInfo(localDir);
                    List<FileInfo> lastFiles = new List<FileInfo>();
                    DirectoryInfo[] historyVers = baseDir.GetDirectories();
                    DirectoryInfo lastDir = historyVers.Where(it => it.Name.Contains("V0.0") == false).OrderBy(it => it.CreationTime).LastOrDefault();
                    if (lastDir != null)
                    {
                        GetAllFiles(lastDir.FullName, ref lastFiles);
                    }
                    int row = (int)button.GetValue(Grid.RowProperty);
                    int column = (int)button.GetValue(Grid.ColumnProperty);
                    CircleBarModel barModel = new CircleBarModel();
                    CircleBarView bar = new CircleBarView(barModel);
                    bar.SetValue(Grid.RowProperty, row);
                    bar.SetValue(Grid.ColumnProperty, column);               
                    new Thread((Action) =>
                    {
                        try
                        {
                            SoftGrid.Dispatcher.Invoke((Action)delegate
                            {
                                SoftGrid.Children.Add(bar);
                            });
                            string zip = Download(model.FtpPath, localDir, barModel, bar);
                            Decompress(zip, localDir, barModel, bar,model.AppName+"V0.0");
                            Dispatcher.Invoke((Action)delegate
                            {
                                barModel.text = "95%";
                                barModel.date = barModel.GetValue(95);
                            });
                            string[] changeFiles = new string[] { };
                            if (model.ConfigPathList != null)
                            {
                                changeFiles = model.ConfigPathList.Split(';');
                            }
                            int a = 0;
                            foreach (FileInfo lastFile in lastFiles)
                            {
                                //todo 配置文件
                                if (changeFiles.Contains(lastFile.FullName.Replace(lastDir?.FullName, "")))
                                {
                                    string replaceFile = localDir + "\\" + model.AppName + "V0.0" + lastFile.FullName.Replace(lastDir?.FullName, "");
                                    //todo 文件夹复制
                                    if (File.Exists(replaceFile))
                                    {
                                        File.Delete(replaceFile);
                                    }
                                    File.Copy(lastFile.FullName, replaceFile);
                                }
                                Dispatcher.Invoke((Action)delegate
                                {
                                    int value = a * 5 / lastFiles.Count + 95;
                                    barModel.text = value.ToString() + "%";
                                    barModel.date = barModel.GetValue(value);
                                });
                            }
                            SoftGrid.Dispatcher.Invoke((Action)delegate
                            {
                                SoftGrid.Children.Remove(bar);
                            });
                        }
                        catch (Exception ee)
                        {
                            SoftGrid.Dispatcher.Invoke((Action)delegate
                            {
                                SoftGrid.Children.Remove(bar);
                                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                                LogHelper.WriteLog(ee.ToString());
                            });
                        }
                    }).Start();
                }

                else if (button.Background == Status.Operational)
                {
                    Process process1 = new Process();
                    process1.StartInfo.WorkingDirectory = exePath.Substring(0, exePath.LastIndexOf('\\'));
                    process1.StartInfo.FileName = exePath.Substring(exePath.LastIndexOf('\\') + 1);
                    Sql3Helper.MX_AppRunRecord mX_Run = new Sql3Helper.MX_AppRunRecord()
                    {
                        Appid = model.id,
                        AppName = model.AppName,
                        Customer = model.Customer,
                        Product = model.Product,
                        Version = model.Version
                    };
                    if (string.IsNullOrEmpty(model.Login) == false)
                    {
                        var view = new View.LogInView(model.Login);
                        bool? isIn = view.ShowDialog();
                        this.Focus();
                        if (isIn == false)
                        {
                            return;
                        }
                        mX_Run.User = MainWindow.userModel?.nickName;
                    }
                    runDAL.InsertMX_AppRunRecord(mX_Run);
                    process1.Start();
                    _mainWindow.WindowState = WindowState.Minimized;
                }
                else
                {
                    int row = (int)button.GetValue(Grid.RowProperty);
                    int column = (int)button.GetValue(Grid.ColumnProperty);
                    CircleBarModel barModel = new CircleBarModel();
                    CircleBarView bar = new CircleBarView(barModel);
                    bar.SetValue(Grid.RowProperty, row);
                    bar.SetValue(Grid.ColumnProperty, column);
                    if (button.Background == Status.NotDownloaded)
                    {
                        new Thread((Action) =>
                        {
                            try
                            {
                                SoftGrid.Dispatcher.Invoke((Action)delegate
                                {
                                    SoftGrid.Children.Add(bar);
                                });
                                string zip = Download(model.FtpPath, localDir, barModel, bar);
                                Decompress(zip, zip.Substring(0, zip.LastIndexOf('\\')), barModel, bar, string.IsNullOrEmpty( model.LocalPath) ? null : "");
                                Dispatcher.Invoke((Action)delegate
                                {
                                    barModel.text = "100%";
                                    barModel.date = barModel.GetValue(100);
                                });
                                SoftGrid.Dispatcher.Invoke((Action)delegate
                                {
                                    SoftGrid.Children.Remove(bar);
                                    button.Name = button.Name.Replace("FTP", "LOCAL");
                                    button.Background = Status.Operational;
                                });
                            }
                            catch (Exception ee)
                            {
                                Dispatcher.Invoke((Action)delegate
                                {
                                    SoftGrid.Children.Remove(bar);
                                    HandyControl.Controls.Growl.Error(ee.Message.ToString());
                                    LogHelper.WriteLog(ee.ToString());
                                });
                            }

                        }).Start();
                    }
                    else if (button.Background == Status.NotUpgraded)
                    {
                        List<FileInfo> lastFiles = new List<FileInfo>();
                        DirectoryInfo lastDir = null;
                        if (string.IsNullOrEmpty(model.LocalPath))
                        {
                            DirectoryInfo baseDir = new DirectoryInfo(localDir);
                            DirectoryInfo[] historyVers = baseDir.GetDirectories();
                            lastDir = historyVers.Where(it => it.Name.Contains("V0.0") == false).OrderBy(it => it.CreationTime).LastOrDefault();
                            if (lastDir != null)
                            {
                                GetAllFiles(lastDir.FullName, ref lastFiles);
                            }
                        }
                        else
                        {
                            string ver = Directory.GetFiles(localDir).FirstOrDefault(it => it.Contains(".zip") && it.Contains(model.AppName))?.Replace(".zip", "").Replace(localDir + "\\" + model.AppName, "");
                            if (string.IsNullOrEmpty(ver))
                            {
                                ver = "V0.0";
                            }
                            if (Directory.Exists(model.LocalPath + ver))
                            {
                                Directory.Delete(model.LocalPath + ver, true);
                            }
                            Directory.Move(model.LocalPath, model.LocalPath + ver);
                            Directory.CreateDirectory(model.LocalPath);
                            lastDir = new DirectoryInfo(model.LocalPath + ver);
                            if (lastDir != null)
                            {
                                GetAllFiles(lastDir.FullName, ref lastFiles);
                            }
                        }
                        new Thread((Action) =>
                        {
                            try
                            {

                                SoftGrid.Dispatcher.Invoke((Action)delegate
                                {
                                    SoftGrid.Children.Add(bar);
                                });
                                string zip = Download(model.FtpPath, localDir, barModel, bar);
                                Decompress(zip, localDir, barModel, bar, string.IsNullOrEmpty(model.LocalPath) ? null : "");
                                Dispatcher.Invoke((Action)delegate
                                {
                                    barModel.text = "95%";
                                    barModel.date = barModel.GetValue(95);
                                });
                                string[] changeFiles = new string[] { };
                                if (model.ConfigPathList != null)
                                {
                                    changeFiles = model.ConfigPathList.Split(';');
                                }
                                int a = 0;
                                foreach (FileInfo lastFile in lastFiles)
                                {
                                    if (changeFiles.Contains(lastFile.FullName.Replace(lastDir.FullName, "")))
                                    {
                                        string replaceFile = localDir + "\\" + model.AppName + model.Version + lastFile.FullName.Replace(lastDir.FullName, "");
                                        if (string.IsNullOrEmpty(model.LocalPath) == false)
                                        {
                                            replaceFile = localDir + "\\" + lastFile.FullName.Replace(lastDir.FullName, "");
                                        }
                                        //if (File.Exists(replaceFile))
                                        //{
                                        //    File.Delete(replaceFile);
                                        //}
                                        File.Copy(lastFile.FullName, replaceFile,true);
                                    }
                                    Dispatcher.Invoke((Action)delegate
                                    {
                                        int value = a * 5 / lastFiles.Count + 95;
                                        barModel.text = value.ToString() + "%";
                                        barModel.date = barModel.GetValue(value);
                                    });
                                }
                                SoftGrid.Dispatcher.Invoke((Action)delegate
                                {
                                    SoftGrid.Children.Remove(bar);
                                    button.Name = button.Name.Replace("FTP", "LOCAL");
                                    button.Background = Status.Operational;
                                });
                            }
                            catch (Exception ee)
                            {
                                SoftGrid.Dispatcher.Invoke((Action)delegate
                                {
                                    SoftGrid.Children.Remove(bar);
                                    HandyControl.Controls.Growl.Error(ee.Message.ToString());
                                    LogHelper.WriteLog(ee.ToString());
                                });
                            }
                        }).Start();
                    }
                }
            }
            catch (Exception ee)
            {
                
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString() );
            }

        }

        private string path = "ftp://cquni.com//";    //目标路径
        private string username = "yfgc";   //ftp用户名
        private string password = "yfgc";   //ftp密码
        public string Download(string fileName, string localPath, CircleBarModel barModel,CircleBarView bar)
        {
            try
            {
                FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + fileName));
                req.Method = WebRequestMethods.Ftp.GetFileSize;
                req.UseBinary = true;
                req.Credentials = new NetworkCredential(username, password);
                req.UsePassive = false;
                FtpWebResponse res = (FtpWebResponse)req.GetResponse();
                long cl = res.ContentLength;
                Dispatcher.Invoke((Action)delegate
                {
                    barModel.text = "5%";
                    barModel.date = barModel.GetValue(5);
                });
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.UsePassive = false;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                Stream ftpStream = response.GetResponseStream();
                long lenth = 0;
                int bufferSize = 2048;
                int readCount = 2048;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);

                Dispatcher.Invoke((Action)delegate
                {
                    barModel.text = "10%";
                    barModel.date = barModel.GetValue(10);
                });
                if (!Directory.Exists(localPath))
                {
                    Directory.CreateDirectory(localPath);
                }
                using (FileStream outputStream = new FileStream(localPath + fileName.Substring(fileName.LastIndexOf('\\')), FileMode.Create))
                {
                    ftpStream.ReadTimeout = 3000;
                    try
                    {
                        while (readCount > 0)
                        {
                            outputStream.Write(buffer, 0, readCount);
                            readCount = ftpStream.Read(buffer, 0, bufferSize);
                            lenth += readCount;
                            int value = (int)(lenth * 71 / cl) + 10;
                            Dispatcher.Invoke((Action)delegate
                            {
                                barModel.text = value.ToString("0") + "%";
                                barModel.date = barModel.GetValue(value);
                            });
                        }
                    }
                    catch (Exception)
                    {
                    }
                    if (outputStream.Length < cl)
                    {
                        throw new Exception("文件下载失败");
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    response.Close();

                    return outputStream.Name;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void Decompress(string GzipFile, string targetPath, CircleBarModel barModel, CircleBarView bar,string replace=null)
        {
            string directoryName = targetPath;
            if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录    
            string CurrentDirectory = directoryName;
            byte[] data = new byte[2048];
            int size = 2048;
            ZipEntry theEntry = null;
            long count;
            using (FileStream fsFile = new FileStream(GzipFile, FileMode.OpenOrCreate))
            { 
                ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(fsFile);
                count = zipFile.Count;
            }

            using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))
            {
                int num = 0;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string name = theEntry.Name;
                    if (replace != null)
                    {
                        name = replace + theEntry.Name.Substring(theEntry.Name.IndexOf('/') + (replace == "" ? 1 : 0));
                    }
                    num++;
                    if (theEntry.IsDirectory)
                    {// 该结点是目录    
                        if (!Directory.Exists(CurrentDirectory +"\\"+ name))
                            Directory.CreateDirectory(CurrentDirectory + "\\" + name);
                    }
                    else
                    {
                        if (name != String.Empty)
                        {
                            //  检查多级目录是否存在  
                            if (name.Contains("/"))
                            {
                                string parentDirPath = name.Remove(name.LastIndexOf("/") + 1);
                                if (!Directory.Exists(CurrentDirectory + "\\" + parentDirPath))
                                {
                                    Directory.CreateDirectory(CurrentDirectory + "\\" + parentDirPath);
                                }
                            }

                            //解压文件到指定的目录    
                            using (FileStream streamWriter = File.Create(CurrentDirectory + "\\" + name))
                            {
                                int lenth = 0;
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size <= 0) break;
                                    streamWriter.Write(data, 0, size);
                                    lenth += size;
                                }
                                streamWriter.Close();
                            }
                        }
                    }
                    int value = (int)(num * 19 / count) + 80;
                    Dispatcher.Invoke((Action)delegate
                    {
                        barModel.text = value.ToString("0") + "%";
                        barModel.date = barModel.GetValue(value);
                    });
                }
                s.Close();
            }
        }
        public void GetAllFiles(string path, ref List<FileInfo> files)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            FileInfo[] allFile = dir.GetFiles();
            foreach (FileInfo fi in allFile)
            {
                if (fi.Name.Contains(".pdb"))
                {
                    continue;
                }
                files.Add(fi);
            }
            DirectoryInfo[] allDir = dir.GetDirectories();
            foreach (DirectoryInfo d in allDir)
            {
                GetAllFiles(d.FullName, ref files);
            }
        }

    }
}
